#!/bin/sh

cd ${JIANMU_WORKSPACE} && pwd

# 登录到指定的 Docker Registry
if [[ ! -z "${JIANMU_DOCKER_USERNAME}" ]]; then 
    docker login -u ${JIANMU_DOCKER_USERNAME} -p ${JIANMU_DOCKER_PASSWORD} ${JIANMU_REGISTRY_ADDRESS}; 
fi

set -x 
docker_build_arg=""
no_cache=""
if [[ ! -z "${JIANMU_BUILD_ARGS}" ]]; then
    build_args=$(echo ${JIANMU_BUILD_ARGS} | tr ',' ' ')
    for arg in ${build_args}
    do
      docker_build_arg="${docker_build_arg} --build-arg ${arg}"
    done
fi

if [[ "${JIANMU_NO_CACHE}" == "true" ]]
then
    no_cache="--no-cache"
fi

# 构建镜像
# 确保镜像名称中包含 Registry 地址
if [[ -z "${JIANMU_REGISTRY_ADDRESS}" ]]; then
    # 如果没有指定 Registry 地址，默认使用 Docker Hub
    full_image_name="${JIANMU_IMAGE_NAME}:${JIANMU_IMAGE_TAG}"
else
    # 如果指定了 Registry 地址，将其包含在镜像名称中
    full_image_name="${JIANMU_REGISTRY_ADDRESS}/${JIANMU_IMAGE_NAME}:${JIANMU_IMAGE_TAG}"
fi

docker build ${no_cache} -f ${JIANMU_DOCKER_FILE} -t ${full_image_name} ${docker_build_arg} ${JIANMU_DOCKER_BUILD_PATH}

# 推送镜像
if [[ $? -eq 0 ]]; then
    docker push ${full_image_name}
fi

# 清理本地镜像
if [[ "${JIANMU_IMAGE_CLEAN}" == "true" ]]; then
    docker rmi ${full_image_name} || true
fi

# 输出结果
echo "{\"image_name\": \"${JIANMU_IMAGE_NAME}\",\"image_tag\": \"${JIANMU_IMAGE_TAG}\"}" > /tmp/result.json